<template>
    <view class="edit-purchase-container">
        <!-- Loading State -->
        <view v-if="isLoading" class="loading-state">
            <u-loading-icon mode="circle" size="30"></u-loading-icon>
            <text>加载中...</text>
        </view>

        <template v-if="!isLoading && formData.id">
            <!-- 基础信息编辑 -->
            <view class="info-section card">
                <view class="info-item clickable" @click="showDatePicker = true">
                    <text class="label">日期</text>
                    <view class="value-select">
                        <text>{{ formData.businessDate | formatDate }}</text>
                        <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
                    </view>
                </view>
                <view class="info-item clickable" @click="selectSupplier">
                    <text class="label">供应商</text>
                    <view class="value-select">
                        <text :class="{ 'placeholder': !selectedSupplierName }">
                            {{ selectedSupplierName || '请选择供应商' }}
                        </text>
                        <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
                    </view>
                </view>
            </view>

            <!-- 商品信息编辑 -->
            <view class="goods-section card">
                <view class="section-header">
                    <text>选中货品 ({{ formData.purchaseDetailItemList ? formData.purchaseDetailItemList.length : 0
                        }})</text>
                    <text>合计金额: ¥{{ totalAmount | formatAmount }}</text>
                </view>
                <view class="goods-list">
                    <view class="goods-item" v-for="(item, index) in formData.purchaseDetailItemList" :key="index">
                        <view class="goods-image">
                            <image :src="item.goodsImage || item.imageUrl || '/static/images/default-goods.png'"
                                mode="aspectFill"></image>
                        </view>
                        <view class="goods-info">
                            <view class="name">{{ item.goodsName || '商品名称' }}</view>
                            <!-- 可编辑的数量和单价 -->
                            <view class="editable-detail">
                                <view class="edit-item">
                                    <text>数量:</text>
                                    <u-input type="digit" v-model.number="item.quantity"
                                        @change="handleQuantityChange(item)" border="none" inputAlign="right"
                                        customStyle="padding: 0 10rpx;"></u-input>
                                </view>
                                <view class="edit-item">
                                    <text>单价: ¥</text>
                                    <u-input type="digit" v-model.number="item.unitPrice"
                                        @change="handlePriceChange(item)" border="none" inputAlign="right"
                                        customStyle="padding: 0 10rpx;"></u-input>
                                </view>
                            </view>
                            <view class="price-amount">
                                <text>金额: ¥{{ item.totalPrice | formatAmount }}</text>
                                <!-- <u-icon name="trash" color="#fa3534" size="20" @click="removeGoodsItem(index)"
                                    customStyle="margin-left: 20rpx;"></u-icon> -->
                            </view>
                        </view>
                    </view>
                    <view v-if="!formData.purchaseDetailItemList || formData.purchaseDetailItemList.length === 0"
                        class="empty-goods">
                        <text>请添加商品</text>
                    </view>
                    <view class="add-goods-btn" @click="addGoods">
                        <u-icon name="plus" size="40" color="#39C9BB"></u-icon>
                    </view>
                </view>
            </view>

            <!-- 结算信息编辑 -->
            <view class="settlement-section card">
                <view class="settlement-item input-item">
                    <text class="label">折扣率</text>
                    <view class="discount-input-container">
                        <input type="digit" class="settlement-input short-input" v-model="formData.discountRate" placeholder="100" @blur="handleDiscountRateBlur" />
                        <text class="percent-sign">%</text>
                    </view>
                </view>
                <view class="settlement-item input-item">
                    <text class="label">折后应付</text>
                    <input type="number" class="settlement-input" v-model="formData.discountedAmount" placeholder="0.00" @blur="handleDiscountedAmountBlur" />
                </view>
                <view class="settlement-item input-item">
                    <text class="label">本单实付</text>
                    <input type="number" class="settlement-input" v-model="formData.actualPayment" placeholder="0.00" />
                </view>
                <view class="settlement-item clickable" @click="selectAccount">
                    <text class="label">结算账户</text>
                    <view class="value-select">
                        <text>{{ formData.paymentMethod || '请选择账户' }}</text>
                        <u-icon name="arrow-right" size="24" color="#c0c4cc"></u-icon>
                    </view>
                </view>
            </view>

            <!-- 备注信息编辑 -->
            <view class="remark-section card">
                <view class="section-header">
                    <text class="label">备注</text>
                    <text class="code">单号: {{ formData.orderCode || '无' }}</text>
                </view>
                <textarea class="remark-input" v-model="formData.remark" placeholder="请输入备注信息"
                    maxlength="200"></textarea>
            </view>
        </template>

        <view v-if="!isLoading && !formData.id" class="empty-state">
            <u-empty mode="data" text="无法加载进货单数据"></u-empty>
        </view>

        <!-- 底部操作按钮 -->
        <view class="footer-actions">
            <button class="btn-delete" @click="confirmDeletePurchase">删除</button>
            <button class="btn-save" @click="savePurchase">保存</button>
        </view>

        <!-- Pickers -->
        <u-datetime-picker :show="showDatePicker" v-model="currentDate" mode="date" @confirm="confirmDate"
            @cancel="showDatePicker = false"></u-datetime-picker>

        <u-picker :show="showSupplierPicker" :columns="[supplierColumns]" keyName="label" @confirm="confirmSupplier"
            @cancel="cancelPicker"></u-picker>

        <u-picker :show="showAccountPicker" :columns="[accountColumns]" keyName="label" @confirm="confirmAccount"
            @cancel="cancelPicker"></u-picker>

        <!-- Delete Confirmation Modal -->
        <u-modal :show="deleteModalVisible" content="确定要删除该进货单吗？此操作不可恢复。" :showCancelButton="true"
            @confirm="deletePurchase" @cancel="deleteModalVisible = false"></u-modal>
    </view>
</template>

<script>
import api from '@/utils/api.js';

export default {
    data() {
        return {
            purchaseId: null,
            formData: {
                id: null,
                businessDate: '',
                supplierId: null,
                supplierName: '', // 用于显示，提交时可能不需要
                purchaseDetailItemList: [],
                totalAmount: 0,
                discountRate: 100, // 折扣率
                discountedAmount: 0, // 折后金额
                actualPayment: 0,
                accountId: '现金', // 默认结算账户
                remark: '',
                orderCode: '', // 单据编号，通常是只读
                // 根据需要添加字段
            },
            isLoading: true,
            deleteModalVisible: false,
            // Picker states
            showDatePicker: false,
            showSupplierPicker: false,
            showAccountPicker: false,
            currentDate: Number(new Date()), // 用于日期选择器初始化
            selectedSupplierName: '', // 用于显示选中供应商名称
            supplierColumns: [],
            accountColumns: [
                { label: '现金', value: '现金' },
                { label: '微信', value: '微信' },
                { label: '支付宝', value: '支付宝' },
                { label: '银行卡', value: '银行卡' },
                { label: '其他账户', value: '其他账户' }
            ],
            skipWatchers: false, // 防止初始化时触发计算
        };
    },
    filters: {
        formatDate(value) {
            if (!value) return '';
            try {
                const date = new Date(value);
                if (isNaN(date.getTime())) return value.toString().split('T')[0];
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            } catch (e) {
                return value.toString().split('T')[0];
            }
        },
        formatAmount(value) {
            const num = Number(value);
            return isNaN(num) ? '0.00' : num.toFixed(2);
        }
    },
    computed: {
        // 计算合计金额
        totalAmount() {
            return this.formData.purchaseDetailItemList.reduce((sum, item) => {
                return sum + Number(item.totalPrice || 0);
            }, 0);
        }
    },
    watch: {
        // 监听商品列表变化，自动计算总价
        'formData.purchaseDetailItemList': {
            handler() {
                if (!this.skipWatchers) {
                    this.recalculateAmounts();
                }
            },
            deep: true
        },
    },
    onLoad(options) {
        uni.$on('confirmSelectGoods', this.handleGoodsSelection);
        if (options.id) {
            this.purchaseId = options.id;
            this.formData.id = options.id;
            uni.setNavigationBarTitle({ title: '编辑进货单' });
            this.loadInitialData();
        } else {
            // 通常编辑页必须有ID
            uni.showToast({
                title: '无效的进货单ID',
                icon: 'none'
            });
            this.isLoading = false;
            setTimeout(() => uni.navigateBack(), 1500);
        }
    },
    onUnload() {
        uni.$off('confirmSelectGoods', this.handleGoodsSelection);
    },
    methods: {
        // 统一加载初始数据
        async loadInitialData() {
            this.isLoading = true;
            this.skipWatchers = true; // 禁用watchers
            try {
                await this.loadPurchaseDetail();
                await this.loadSuppliers();
            } catch (err) {
                console.error("加载初始数据失败:", err);
                uni.showToast({ title: '加载数据失败', icon: 'none' });
            } finally {
                this.isLoading = false;
                // 延迟启用watchers，确保数据渲染完成
                setTimeout(() => { this.skipWatchers = false; }, 300);
            }
        },

        async loadPurchaseDetail() {
            if (!this.purchaseId) return;
            console.log('加载进货单详情...');
            try {
                if (!api.getPurchaseDetail) {
                    throw new Error('API函数getPurchaseDetail未定义');
                }
                const res = await api.getPurchaseDetail(this.purchaseId);
                console.log('进货单详情结果:', res);
                const goodsList = await api.getGoodsListByReceiptCode(res.receiptCode);
                console.log('商品列表结果:', goodsList);

                if (res) {
                    this.formData = {
                        ...this.formData,
                        ...res,
                        businessDate: res.businessDate || new Date().toISOString().split('T')[0],
                        purchaseDetailItemList: goodsList,
                        discountRate: parseFloat(res.discountRate || res.discount || 100), // 兼容discountRate或discount
                        discountedAmount: parseFloat(res.discountedAmount || 0),
                        actualPayment: parseFloat(res.actualPayment || 0),
                    };
                    this.currentDate = new Date(this.formData.businessDate).getTime(); // 初始化日期选择器
                    this.selectedSupplierName = res.supplierName || ''; // 设置初始供应商名称显示
                    // 如果初始没有折后金额，根据折扣率计算一次
                    if (!this.formData.discountedAmount && this.formData.discountRate !== 100) {
                        this.calculateDiscountedAmount();
                    }
                    console.log(1,this.formData)
                } else {
                    throw new Error('获取详情数据为空或格式错误');
                }
            } catch (err) {
                console.error('加载进货单详情失败:', err);
                uni.showToast({ title: `加载详情失败: ${err.message}`, icon: 'none' });
                // 加载失败，阻止后续操作或返回
                this.formData.id = null;
            }
        },

        // 加载供应商列表
        async loadSuppliers() {
            console.log('加载供应商列表...');
            try {
                if (!api.listSupplier) {
                    throw new Error('API函数listSupplier未定义');
                }
                const res = await api.listSupplier({ pageNum: 1, pageSize: 1000 });
                if (res && res.rows && Array.isArray(res.rows)) {
                    this.supplierColumns = res.rows.map(s => ({
                        label: s.supplierName || '未命名供应商',
                        value: s.supplierId // 确保使用正确的ID字段 (根据你的API调整，可能是id或supplierId)
                    }));
                    // 如果当前有 supplierId，尝试匹配设置 selectedSupplierName
                    if (this.formData.supplierId) {
                        const found = this.supplierColumns.find(s => s.value === this.formData.supplierId);
                        if (found) {
                            this.selectedSupplierName = found.label;
                        } else if (!this.selectedSupplierName) {
                            // 如果API返回的supplierName不可靠，这里可以留空或显示ID
                            this.selectedSupplierName = ``; // 或 `ID: ${this.formData.supplierId}`
                        }
                    }
                } else {
                    this.supplierColumns = [];
                }
            } catch (err) {
                console.error('加载供应商列表失败:', err);
                uni.showToast({ title: '加载供应商失败', icon: 'none' });
                this.supplierColumns = [];
            }
        },

        // --- Picker Handlers ---
        confirmDate(e) {
            this.formData.businessDate = this.formatDateToString(e.value);
            this.currentDate = e.value;
            this.showDatePicker = false;
        },
        selectSupplier() {
            if (!this.supplierColumns || this.supplierColumns.length === 0) {
                uni.showToast({ title: '供应商列表加载中或为空\n请稍后重试', icon: 'none' });
                this.loadSuppliers(); // 尝试重新加载
                return;
            }
            this.showSupplierPicker = true;
        },
        confirmSupplier(e) {
            if (e && e.value && e.value.length > 0) {
                const selected = e.value[0];
                this.formData.supplierId = selected.value; // value 应该是供应商ID
                this.selectedSupplierName = selected.label; // label 是供应商名称
            }
            this.showSupplierPicker = false;
        },
        selectAccount() {
            this.showAccountPicker = true;
        },
        confirmAccount(e) {
            if (e && e.value && e.value.length > 0) {
                this.formData.paymentMethod = e.value[0].value; // 使用value
            }
            this.showAccountPicker = false;
        },
        cancelPicker() {
            this.showDatePicker = false;
            this.showSupplierPicker = false;
            this.showAccountPicker = false;
        },
        formatDateToString(dateInput) {
            if (!dateInput) return '';
            try {
                const date = new Date(dateInput);
                if (isNaN(date.getTime())) return '';
                const year = date.getFullYear();
                const month = String(date.getMonth() + 1).padStart(2, '0');
                const day = String(date.getDate()).padStart(2, '0');
                return `${year}-${month}-${day}`;
            } catch (e) { return ''; }
        },

        // --- Goods Handlers ---
        addGoods() {
            uni.navigateTo({ url: '/pages/goods/select' });
        },
        setSelectedGoods(goods, amount) { // This now needs to update currentState
            // Update the *current* state object
            console.log("--- 选择商品 ---", goods,amount)
            // this.currentState.selectedGoodsList = goods;
            // this.currentState.selectedGoodsCount = goods.length;
            this.formData.totalAmount = amount;

            // Calculate discount based on the current state
            // this.calculateDiscount(); // Needs to use currentState too
            this.formData.purchaseDetailItemList = goods.map(item => ({
                ...item,
                goodsId: item.id,
                goodsCode: item.id,
                goodsName: item.name,
                unitPrice: item.price,
                totalPrice: item.price * item.quantity,
                // finalPrice: item.price * item.quantity,
            }));
            this.recalculateAmounts()
            uni.showToast({
                title: `已选择${goods.length}种商品`,
                icon: 'none',
                duration: 1500
            });
        },
        handleGoodsSelection(selectedGoods) {
            console.log('收到选择的商品:', selectedGoods);
            if (!Array.isArray(selectedGoods)) {
                selectedGoods = [selectedGoods];
            }
            selectedGoods.forEach(newItem => {
                const existingItem = this.formData.purchaseDetailItemList.find(item => item.goodsId === newItem.id);
                const quantity = parseFloat(newItem.quantity || 1);
                const unitPrice = parseFloat(newItem.price || 0);
                const totalPrice = parseFloat((quantity * unitPrice).toFixed(2));

                if (existingItem) {
                    existingItem.quantity += quantity;
                    existingItem.totalPrice = parseFloat((existingItem.quantity * existingItem.unitPrice).toFixed(2));
                    console.log(`更新商品数量: ${existingItem.goodsName}, 新数量: ${existingItem.quantity}`);
                } else {
                    console.log(`添加新商品: ${newItem.name}`);
                    this.formData.purchaseDetailItemList.push({
                        goodsId: newItem.id,
                        goodsCode: newItem.code || '',
                        goodsName: newItem.name || '未知商品',
                        goodsSpec: newItem.spec || '',
                        imageUrl: newItem.image || null,
                        quantity: quantity,
                        unitPrice: unitPrice,
                        totalPrice: totalPrice,
                        // finalPrice: totalPrice // 进货通常不用finalPrice?
                    });
                }
            });
            // this.recalculateAmounts(); // watch会自动触发
        },
        removeGoodsItem(index) {
            this.formData.purchaseDetailItemList.splice(index, 1);
            // this.recalculateAmounts(); // watch会自动触发
        },
        handleQuantityChange(item) {
            item.quantity = parseFloat(item.quantity) || 0;
            if (item.quantity < 0) item.quantity = 0;
            item.totalPrice = parseFloat((item.quantity * item.unitPrice).toFixed(2));
            // this.recalculateAmounts(); // watch会自动触发
        },
        handlePriceChange(item) {
            item.unitPrice = parseFloat(item.unitPrice) || 0;
            if (item.unitPrice < 0) item.unitPrice = 0;
            item.totalPrice = parseFloat((item.quantity * item.unitPrice).toFixed(2));
            // this.recalculateAmounts(); // watch会自动触发
        },

        // --- Calculation Handlers ---
        recalculateAmounts() {
            const total = this.totalAmount; // 使用计算属性获取最新总价
            this.calculateDiscountedAmount(total);
        },
        calculateDiscountedAmount(total = this.totalAmount) {
            let rate = parseFloat(this.formData.discountRate);
            // 添加详细日志
            console.log(`calculateDiscountedAmount - total: ${total}, rate from formData: ${this.formData.discountRate}, parsed rate: ${rate}`);
            
            if (isNaN(rate) || rate < 0) rate = 0;
            if (rate > 100) rate = 100;
            
            // 在计算前再次确认 total 是否有效
            if (isNaN(total) || total <= 0) {
                console.warn("calculateDiscountedAmount - totalAmount无效，无法计算折后金额");
                this.formData.discountedAmount = 0; // 直接设为0
                return; // 提前退出
            }

            this.formData.discountedAmount = parseFloat((total * (rate / 100)).toFixed(2));
            console.log(`计算折后金额结果: ${this.formData.discountedAmount} (总额: ${total}, 折扣率: ${rate}%)`);
        },
        calculateDiscountRate() {
            const total = this.totalAmount;
            let discounted = parseFloat(this.formData.discountedAmount);
            if (isNaN(discounted) || discounted < 0) discounted = 0;
            
            if (total > 0 && discounted >= 0) {
                this.formData.discountRate = parseFloat(((discounted / total) * 100).toFixed(2));
            } else {
                this.formData.discountRate = 100.00;
            }
            console.log(`计算折扣率: ${this.formData.discountRate}% (折后: ${discounted}, 总额: ${total})`);
        },
        handleDiscountRateBlur(e) {
            console.log("折扣率输入框失焦");
            let rate = parseFloat(this.formData.discountRate);
            if (isNaN(rate) || rate < 0) rate = 0;
            if (rate > 100) rate = 100;
            if (this.formData.discountRate !== rate) {
                this.formData.discountRate = rate;
            }
            // 在调用计算前打印 totalAmount
            console.log(`handleDiscountRateBlur - 当前 totalAmount: ${this.totalAmount}`);
            this.calculateDiscountedAmount(); // 使用最新的 totalAmount 计算
        },
        handleDiscountedAmountBlur(e) {
            console.log("折后应付输入框失焦");
            let discounted = parseFloat(this.formData.discountedAmount);
            if (isNaN(discounted) || discounted < 0) discounted = 0;
            if (this.formData.discountedAmount !== discounted) {
                this.formData.discountedAmount = discounted;
            }
            this.calculateDiscountRate();
        },

        // --- Save & Delete ---
        savePurchase() {
            // 1. 验证
            if (!this.formData.supplierId) {
                uni.showToast({ title: '请选择供应商', icon: 'none' });
                return;
            }
            if (!this.formData.purchaseDetailItemList || this.formData.purchaseDetailItemList.length === 0) {
                uni.showToast({ title: '请至少添加一个商品', icon: 'none' });
                return;
            }
            // 验证金额和数量是否有效...
            for (const item of this.formData.purchaseDetailItemList) {
                if (isNaN(item.quantity) || item.quantity <= 0) {
                    uni.showToast({ title: `商品 ${item.goodsName} 数量无效`, icon: 'none' });
                    return;
                }
                if (isNaN(item.unitPrice) || item.unitPrice < 0) {
                    uni.showToast({ title: `商品 ${item.goodsName} 单价无效`, icon: 'none' });
                    return;
                }
            }

            uni.showLoading({ title: '保存中...' });

            // 2. 准备数据
            const postData = {
                id: this.purchaseId,
                businessDate: this.formData.businessDate,
                supplierId: this.formData.supplierId,
                totalAmount: this.totalAmount, // 使用计算属性的总价
                discount: parseFloat(this.formData.discountRate || 100),
                discountedAmount: parseFloat(this.formData.discountedAmount || 0),
                actualPayment: parseFloat(this.formData.actualPayment || 0),
                paymentMethod: this.formData.accountId,
                remark: this.formData.remark || '',
                // operation: 'purchase', // 后端更新接口通常不需要operation
                purchaseDetailItemList: this.formData.purchaseDetailItemList.map(item => ({
                    id: item.id || null, // 如果明细有ID，需要传递用于更新
                    goodsId: item.goodsId,
                    quantity: parseFloat(item.quantity || 0),
                    unitPrice: parseFloat(item.unitPrice || 0),
                    totalPrice: parseFloat(item.totalPrice || 0),
                    // 确保传递后端需要的字段，如 goodsCode, goodsName 等
                    goodsCode: item.goodsCode || '',
                    goodsName: item.goodsName || '',
                    goodsSpec: item.goodsSpec || '',
                    imageUrl: item.imageUrl || '' // 可选
                }))
            };

            console.log("准备更新进货单数据:", JSON.stringify(postData, null, 2));

            // 3. 调用API (假设存在 updatePurchase)
            if (!api.updatePurchase) {
                uni.hideLoading();
                uni.showToast({ title: '更新进货单API未定义', icon: 'none' });
                console.error('API function updatePurchase is not defined');
                return;
            }

            api.updatePurchase({...this.formData})
                .then(res => {
                    uni.hideLoading();
                    uni.showToast({ title: '修改成功', icon: 'success' });
                    uni.navigateBack(-1);
                })
                .catch(err => {
                    uni.hideLoading();
                    console.error("更新进货单失败:", err);
                    uni.showToast({ title: '修改失败，请重试', icon: 'none' });
                });
        },

        confirmDeletePurchase() {
            this.deleteModalVisible = true;
        },
        deletePurchase() {
            if (!this.purchaseId) return;
            this.deleteModalVisible = false;
            uni.showLoading({ title: '删除中...' });
            console.log(`正在删除进货单 ID: ${this.purchaseId}`);

            if (!api.deletePurchase) {
                uni.hideLoading();
                uni.showToast({ title: '删除进货单API未定义', icon: 'none' });
                console.error('API function deletePurchase is not defined');
                return;
            }

            api.deletePurchase(this.purchaseId)
                .then(res => {
                    uni.hideLoading();
                    if (res.code === 200 || res.success) {
                        uni.showToast({ title: '删除成功', icon: 'success' });
                        uni.$emit('refreshDetailList', { type: 'purchase' });
                        // 删除成功后，通常需要跳转回列表页，而不是留在编辑页
                        // uni.navigateBack() 可能会返回到详情页，最好是直接跳回列表
                        // 如果列表是Tab页:
                        // uni.switchTab({ url: '/pages/detail/detail' });
                        // 如果列表是普通页:
                        setTimeout(() => {
                            const pages = getCurrentPages();
                            // 尝试返回两层，如果上一页是详情页的话
                            if (pages.length >= 3) {
                                uni.navigateBack({ delta: 2 });
                            } else {
                                uni.navigateBack(); // 否则只返回一层
                            }
                        }, 1500);
                    } else {
                        console.error("删除失败，API 响应:", res);
                        uni.showToast({ title: res.msg || '删除失败', icon: 'none' });
                    }
                })
                .catch(err => {
                    uni.hideLoading();
                    console.error("删除进货单失败:", err);
                    uni.showToast({ title: '删除失败，请重试', icon: 'none' });
                });
        }
    }
};
</script>

<style lang="scss" scoped>
// 样式基本复用 purchase/detail.vue 和 sales/edit.vue 的样式
// 可以将公共样式提取到 mixin 或公共 css 文件
page {
    background-color: #f5f7fa;
}

.edit-purchase-container {
    padding: 20rpx;
    padding-bottom: 140rpx;
    /* Footer space */
}

.loading-state {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 100rpx 0;
    color: #909399;
    font-size: 28rpx;

    text {
        margin-top: 10rpx;
    }
}

.card {
    background-color: #fff;
    border-radius: 16rpx;
    margin-bottom: 20rpx;
    padding: 24rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

/* Info Section */
.info-section {
    .info-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        min-height: 80rpx;
        font-size: 28rpx;
        border-bottom: 1rpx solid #f0f0f0;

        &:last-child {
            border-bottom: none;
        }

        .label {
            color: #666;
            width: 150rpx;
        }

        .value-select {
            flex: 1;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            text {
                color: #333;
                margin-right: 10rpx;

                &.placeholder {
                    color: #c0c4cc;
                }
            }
        }
    }

    .clickable {
        cursor: pointer;

        &:active {
            background-color: #f8f8f8;
        }
    }
}

/* Goods Section */
.goods-section {
    padding: 0;

    .section-header {
        display: flex;
        justify-content: space-between;
        padding: 25rpx 30rpx;
        font-size: 26rpx;
        color: #666;
        border-bottom: 1rpx solid #f0f0f0;
        margin-bottom: 10rpx;
    }

    .goods-list {
        padding: 10rpx 30rpx 0;

        .goods-item {
            display: flex;
            padding: 20rpx 0;
            border-bottom: 1rpx dashed #eee;

            &:last-child {
                border-bottom: none;
            }

            .goods-image {
                width: 100rpx;
                height: 100rpx;
                margin-right: 20rpx;
                flex-shrink: 0;

                image {
                    width: 100%;
                    height: 100%;
                    border-radius: 8rpx;
                    background-color: #f0f0f0;
                }
            }

            .goods-info {
                flex: 1;

                .name {
                    font-size: 28rpx;
                    color: #333;
                    margin-bottom: 8rpx;
                    font-weight: 500;
                }

                .editable-detail {
                    display: flex;
                    justify-content: space-between;
                    align-items: center; // 垂直居中对齐
                    margin-bottom: 8rpx;

                    .edit-item {
                        display: flex;
                        align-items: center;
                        font-size: 24rpx;
                        color: #666;
                        flex: 1; // 让项目平分空间
                        margin-right: 10rpx; // 项目间距

                        &:last-child {
                            margin-right: 0;
                        }

                        text {
                            margin-right: 5rpx;
                            white-space: nowrap;
                        }

                        .u-input {
                            flex: 1; // 输入框占据剩余空间
                            // 确保输入框有明确的高度和内边距，以便对齐
                            height: 50rpx;
                            padding: 0 10rpx;
                            min-width: 80rpx; // 最小宽度
                            box-sizing: border-box;
                        }
                    }
                }

                .price-amount {
                    display: flex;
                    justify-content: space-between;
                    align-items: center;
                    font-size: 24rpx;
                    color: #888;
                }
            }
        }

        .empty-goods {
            text-align: center;
            color: #999;
            font-size: 26rpx;
            padding: 40rpx 0;
        }

        .add-goods-btn {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 30rpx 0;
            border-top: 1rpx solid #eee;
            margin-top: 10rpx;
        }
    }
}

/* Settlement Section */
.settlement-section {
    .settlement-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        min-height: 80rpx;
        font-size: 28rpx;
        border-bottom: 1rpx solid #f0f0f0;
        padding: 15rpx 0; // 增加垂直内边距

        &:last-child {
            border-bottom: none;
        }

        .label {
            color: #666;
            width: 150rpx;
            flex-shrink: 0;
        }

        // 防止标签被压缩
        .value-select {
            flex: 1;
            display: flex;
            justify-content: flex-end;
            align-items: center;

            text {
                color: #333;
                margin-right: 10rpx;
            }
        }

        &.input-item {
            .settlement-input {
                font-size: 28rpx;
                color: #666;
                text-align: right;
                flex-grow: 1; // 允许输入框增长
                margin-left: 20rpx;
                padding: 5rpx 0;
                min-width: 100rpx;
                border: none;
                background-color: transparent;
            }

            .short-input {
                flex-grow: 0;
                width: 120rpx;
            }

            // 固定宽度输入框不增长
            .percent-sign {
                font-size: 28rpx;
                color: #666;
                margin-left: 5rpx;
            }

            .discount-input-container {
                display: flex;
                align-items: center;
                justify-content: flex-end;
                flex: 1;
            }
        }
    }

    .clickable {
        cursor: pointer;

        &:active {
            background-color: #f8f8f8;
        }
    }
}

/* Remark Section */
.remark-section {
    .section-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15rpx;

        .label {
            font-size: 28rpx;
            color: #333;
        }

        .code {
            font-size: 24rpx;
            color: #999;
        }
    }

    .remark-input {
        width: 100%;
        height: 150rpx;
        background-color: #f8f8f8;
        border-radius: 8rpx;
        padding: 15rpx;
        font-size: 28rpx;
        color: #333333;
        box-sizing: border-box;
    }
}

.empty-state {
    padding-top: 150rpx;
}

/* Footer Actions */
.footer-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    height: 120rpx;
    background-color: #ffffff;
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 15rpx 30rpx calc(15rpx + constant(safe-area-inset-bottom));
    padding: 15rpx 30rpx calc(15rpx + env(safe-area-inset-bottom));
    box-shadow: 0 -4rpx 10rpx rgba(0, 0, 0, 0.05);
    z-index: 100; // 确保在最上层

    button {
        flex: 1;
        height: 70rpx;
        line-height: 70rpx;
        border-radius: 35rpx;
        font-size: 28rpx;
        margin: 0 15rpx;
    }

    .btn-delete {
        border: 1rpx solid #fa3534;
        color: #fa3534;
        background-color: #fff;
    }

    .btn-save {
        background-color: #39C9BB;
        color: #fff;
        border: none;
    }
}
</style>